<script setup lang="ts">
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import HotPanel from './components/HotPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from './components/PageSkeleton.vue'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryPanel = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热点数据
const hotList = ref<HotItem[]>([])
const getHomeHotPanel = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 骨架屏加载
const isLoading = ref(false)
// 页面加载
onLoad(async () => {
  isLoading.value = true
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryPanel(),
    getHomeHotPanel(),
    guessRef.value?.getMore(),
  ])
  isLoading.value = false
})
// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()
// 滚动触底
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefreshrrefresh = async () => {
  // 动画开启
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData()
  //语法优化，减少单线程导致的时间增加
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryPanel(),
    getHomeHotPanel(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false
}
</script>
<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar></CustomNavbar>
  <!-- 滚动容器 -->
  <scroll-view
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefreshrrefresh"
    refresher-enabled
    :refresher-triggered="isTriggered"
    class="scroll-view"
    scroll-y
  >
    <!-- 骨架屏 -->
    <PageSkeleton v-if="isLoading"></PageSkeleton>
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 热点面板 -->
      <HotPanel :list="hotList"></HotPanel>
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>
<style lang="scss">
page {
  background-color: #f7f7f7d5;
}
</style>
